<template>
  <div class="app-container">
    <div class="summary">
      <span style="margin-left: 10px">本月正常出勤：{{ stats.normal }}天，迟到：{{ stats.late }}次，缺勤：{{ stats.absent }}次，早退：{{ stats.early }}次</span>
    </div>

    <div class="search-bar" style="margin: 10px">
      <el-date-picker v-model="form.startDate" type="date" placeholder="开始日期" size="mini" style="margin-right:10px " value-format="yyyy-MM-dd"></el-date-picker>
      <el-date-picker v-model="form.endDate" type="date" placeholder="结束日期" size="mini" style="margin-right:10px" value-format="yyyy-MM-dd"></el-date-picker>
      <el-button type="primary" size="mini" @click="handleQuery">搜索</el-button>
      <el-button type="primary" size="mini" @click="handleClock('in')">上班打卡</el-button>
      <el-button type="primary" size="mini" @click="handleClock('out')">下班打卡</el-button>
    </div>

    <el-table :data="list" style="width: 100%" border fit>
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="userName" label="用户名" min-width="100"/>
      <el-table-column prop="clockInTime" label="上午" min-width="150">
        <template #default="{row}">{{ row.clockInTime || '—' }}</template>
      </el-table-column>
      <el-table-column prop="clockOutTime" label="下午" min-width="150">
        <template #default="{row}">{{ row.clockOutTime || '—' }}</template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="{row}">
          <el-tag :type="tagType(row.status)">{{ statusText(row.status) }}</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
  </div>
</template>

<script>
import { listAttendance, clockInOrOut } from "@/api/attend/attendance";
import { getUserProfile } from "@/api/system/user";

export default {
  data() {
    return {
      form: { startDate: '', endDate: '', userName: '' },
      queryParams: { pageNum: 1, pageSize: 10 },
      list: [],
      total: 0,
      stats: { normal: 0, late: 0, early: 0, absent: 0 },
      isAdmin: false // 添加管理员标识
    };
  },
  created() {
    this.checkAdmin(); // 检查是否为管理员
    this.getList();
  },
  methods: {
    async checkAdmin() {
      try {
        const { data } = await getUserProfile();
        // 根据实际返回数据结构调整判断条件
        this.isAdmin = data.admin === true || data.roles.some(role => role.roleKey === 'admin');
      } catch (err) {
        console.error("获取用户信息失败", err);
      }
    },
    async getList() {
      // 构造查询参数
      const query = {
        ...this.queryParams,
        params: {
          beginTime: this.form.startDate,
          endTime: this.form.endDate
        },
        userName: this.form.userName // 添加用户名查询条件
      };

      const res = await listAttendance(query);
      this.list = res.rows;
      this.total = res.total;
      this.calculateStats();
    },
    calculateStats() {
      this.stats = { normal: 0, late: 0, early: 0, absent: 0 };
      this.list.forEach(item => {
        if (this.stats[item.status] !== undefined) this.stats[item.status]++;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleClock() {
      clockInOrOut().then(res => {
        this.$message.success(res.msg);
        this.getList();
      });
    },
    tagType(status) {
      return { normal: 'success', late: 'warning', early: 'info', absent: 'danger' }[status] || '';
    },
    statusText(status) {
      const statusMap = {
        normal: '正常',
        late: '迟到',
        early: '早退',
        absent: '缺卡'
      };
      return statusMap[status] || status;
    }
  }
};
</script>
